<template>
  <div>
    <h1>文件上传相关</h1>
    <input type="file" @change="onChange" />
    <hr />

    <el-upload
      action="/admin/base/comm/upload"
      multiple
      :limit="3"
      :headers="{
        Authorization: userStore.token
      }"
      list-type="picture-card"
      :on-exceed="handleExceed"
      :before-remove="handleRemove"
      :http-request="handleRequest"
    >
      <el-button>上传</el-button>
    </el-upload>

    <hr />

    <el-form>
      <el-form-item label="正面">
        <!-- 下面代码的写法，$event 应该要在事件处理上才能行。 -->
        <!-- <el-upload :http-request="handleRequestOne('img1', $event)"> -->

        <el-upload
          ref="uploadRef"
          :limit="1"
          :show-file-list="false"
          list-type="picture-card"
          :http-request="(event) => handleRequestOne('img1', event)"
          :on-exceed="handleExceedOne"
        >
          <template #default>
            <div v-if="formModel.img1" class="pic-box">
              <img :src="formModel.img1" />
            </div>
            <el-button v-else>选择</el-button>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="反面">
        <el-upload
          :limit="1"
          :show-file-list="false"
          list-type="picture-card"
          :http-request="(event) => handleRequestOne('img2', event)"
        >
          <el-button>选择</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSaveOne">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import request from '@/utils/request'
import { useUserStore } from '@/stores/user'
import type { UploadFile, UploadInstance, UploadRequestOptions } from 'element-plus'
import { reactive, ref } from 'vue'

const userStore = useUserStore()

function onChange(e: Event) {
  const target = e.target as HTMLInputElement
  console.log(target.files)

  request({
    url: '/admin/base/comm/upload',
    method: 'POST',
    // PS
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: {
      file: target.files?.[0]
    }
  })
    .then((resp) => {
      console.log('成功', resp)
    })
    .catch((error) => {
      console.log('失败', error)
    })
}

function handleRemove(uploadFile: UploadFile) {
  console.log(uploadFile)
  // TODO...
  // 返回 false 或者返回一个 rejected 的 Promise 都会阻止文件的删除
  return false
}

// 超出限制的处理函数
function handleExceed() {
  console.log('超出限制')
}

// 自行处理上传请求
function handleRequest(options: UploadRequestOptions) {
  console.log('handleRequest', options)
  // request()

  return request({
    url: '/admin/base/comm/upload',
    method: 'POST',
    // PS
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: {
      // options.file 就是原始的文件信息对象
      file: options.file
    }
  })
    .then((resp) => {
      console.log('成功', resp)
    })
    .catch((error) => {
      console.log('失败', error)
    })
}

const formModel = reactive({
  img1: '',
  img2: ''
})
// 保存第一套方案
function handleSaveOne() {
  /**
   * 需要的参数是：{
   *    img1: '', // 正面的文件路径后端返回的
   *    img2: '', // 反面的文件路径后端返回的
   * }
   */
}

function handleRequestOne(type: string, options: UploadRequestOptions) {
  console.log(type, 'type')
  console.log(options, 'options')
  return request<any, { code: number; message: string; data: string }>({
    url: '/admin/base/comm/upload',
    method: 'POST',
    // PS
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: {
      // options.file 就是原始的文件信息对象
      file: options.file
    }
  })
    .then((resp) => {
      console.log('成功', resp)
      // 将 resp.data 写入到 formModel.img1 or img2
      formModel[type] = resp.data
    })
    .catch((error) => {
      console.log('失败', error)
    })
}

// 超出限制时会触发的函数
//    files 参数 - 触发该限制函数时选择的文件列表
//    uploadFiles 参数 - 当前已经选择好的文件列表
const uploadRef = ref<UploadInstance | null>(null)
function handleExceedOne(files: any, uploadFiles: any) {
  console.log(files, '===')
  console.log(uploadFiles, '====')
  // 先调用 uploadRef.value.clearFiles 清理已经选择的文件
  uploadRef.value?.clearFiles()
  // 修改自己的 formModel.img1 清空
  formModel.img1 = ''
  // 调用 uploadRef.value.handle 手动选择文件上传
  uploadRef.value?.handleStart(files[0])
}
</script>

<style lang="scss" scoped>
.pic-box {
  width: 100%;
  height: 100%;
  overflow: hidden;

  img {
    display: block;
    width: 100%;
    object-fit: fill;
  }
}
</style>
